import logging

from django.shortcuts import render

# Create your views here.
from fdfs_client.client import get_tracker_conf, Fdfs_client
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.status import HTTP_404_NOT_FOUND, HTTP_500_INTERNAL_SERVER_ERROR, HTTP_400_BAD_REQUEST
from rest_framework.viewsets import ModelViewSet

from config.fastdfsConfig import FASTDFS_SERVER_DOMAIN
from shopping.models import Classification,Commodity,CommodityImg
from .serializers import *
from rest_framework.permissions import IsAuthenticated
from utils.permission import wrap_permission,TeacherPermission

#导入日志器
logger = logging.getLogger(__name__)
#tracker server
tracker_path = get_tracker_conf('utils/fastdfs/client.conf')
client = Fdfs_client(tracker_path)

class ClassificationViewSet(ModelViewSet): #商品分类
    queryset = Classification.objects.filter(is_delete=False,parent=None)
    serializer_class = ParentClassificationSerializer
    permission_classes = [IsAuthenticated]

    @wrap_permission(TeacherPermission)
    def create(self, request, *args, **kwargs):
        return ModelViewSet.create(self, request, *args, **kwargs)

    @wrap_permission(TeacherPermission)
    def update(self, request, *args, **kwargs):
        return ModelViewSet.update(self, request, *args, **kwargs)

    @wrap_permission(TeacherPermission)
    def destroy(self, request, *args, **kwargs):
        return ModelViewSet.destroy(self, request, *args, **kwargs)

    @action(methods=['get'],detail=True)
    def commodity(self,request,pk):
        try:
            classification = Classification.objects.filter(is_delete=False).get(id=pk)
        except Classification.DoesNotExist:
            return  Response(status=HTTP_404_NOT_FOUND)
        classification_attr = 'classification1' #默认为一级分类
        classification_name = classification.name #类名，展示自身的类名
        if classification.parent:
            #纠正修改为子类
            classification_attr = 'classification2' #下面这两句表示的意思是如果你不是一级分类，那就变成二级分类，并且显示你上一级和这级分类的名字
            classification_name = f'{classification.parent.name}--{classification.name}'
        data = getattr(classification,classification_attr).filter(is_delete=False,status=1) #通过getattr获取属性，知道你是一级还是二级分类
        return Response({
            'classification':classification_name,
            'commodity':CommoditySerializer(data,many=True).data
        })


class CommodityViewSet(ModelViewSet): #商品
    queryset = Commodity.objects.filter(is_delete=False)
    serializer_class = CommoditySerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        if self.action == ['list','retrieve']:
            return Commodity.objects.filter(is_delete=False,status=1)
        else:
            return self.queryset

    @wrap_permission(TeacherPermission)
    def create(self, request, *args, **kwargs):
        return ModelViewSet.create(self, request, *args, **kwargs)

    @wrap_permission(TeacherPermission)
    def update(self, request, *args, **kwargs):
        return ModelViewSet.update(self, request, *args, **kwargs)

    @wrap_permission(TeacherPermission)
    def destroy(self, request, *args, **kwargs):
        return ModelViewSet.destroy(self, request, *args, **kwargs)

    @action(methods=['post'],detail=True)
    def img(self,request,pk):
        # 获取需要操作的商品
        try:
            commodity = self.get_queryset().get(id=pk)
        except Commodity.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)
        # 得到上传的文件数据
        file = request.FILES.get('file')
        # 判断是否是图片数据，文件类型是否是图片
        if not file or file.content_type not in ('image/png', 'image/jpeg', 'image.gif'):
            # 不是图片，返回客户端输出错误数据
            return Response(status=HTTP_400_BAD_REQUEST)
        # 是图片，交给fastdfs，存储到可用的storage服务上
        # 得到文件后缀名，如果没有默认用png
        try:
            images_ext_name = file.name.split('.')[-1]
        except Exception as e:
            logger.info('图片拓展名异常： %s' %e)
            images_ext_name = 'png'
        # 上传图片数据，通过字节流
        try:
            upload_res = client.upload_by_buffer(file.read(), file_ext_name=images_ext_name)  # 读取发过来的图片内容，文件名为刚才的文件名
        except Exception as e:
            logger.error('图片上传异常：%s' % e)
            return Response(status=HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            if upload_res.get('Status') != 'Upload successed.':
                logger.warning('图片上传失败：')
                return Response(status=HTTP_500_INTERNAL_SERVER_ERROR)
            # 得到返回的file_id
            image_name = upload_res.get('Remote file_id').decode()
            image_url = FASTDFS_SERVER_DOMAIN + image_name  # 拼接路径

            #保存图片地址
            CommodityImg.objects.create(src=image_url,commodity=commodity)

            #返回
            return Response({'data':image_url})

    # @action(methods=['get'],detail=False)
    # def optimization(self,request): #优选书籍
    #     queryset = self.get_queryset().order_by('-comments').order_by('-create_time')#order_by也是排序的
    #     return Response(self.get_serializer(queryset[:3],many=True).data) #展示前5个数据，先获取序列化器要展示的数据，从查询集里获取前5个.再加上 .data






